package com.sdgakj.web.msg;

import com.sdgakj.entity.Message;
import com.sdgakj.entity.MessageUser;
import com.sdgakj.enums.EnumIsDelete;
import com.sdgakj.enums.EnumMsgType;
import com.sdgakj.service.account.ShiroDbRealm.ShiroUser;
import com.sdgakj.service.msg.MessageService;
import com.sdgakj.service.msg.MessageUserService;
import com.sdgakj.service.user.UserService;
import com.sdgakj.utils.JPushUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import javax.servlet.ServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/msg")
public class MsgController {

    private static final String PAGE_SIZE = "10";
    
    private Logger logger = Logger.getLogger(getClass());
    
	@Autowired
	private MessageService messageService;
	
	@Autowired
	private MessageUserService messageUserService;

	@Autowired
	private UserService userService;
	
	/**
	 * 列表
	 * @param pageNumber 页号
	 * @param pageSize   每页大小
	 * @param sortType   排序字段
	 * @param model			
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/list",method = RequestMethod.GET)
	public String list(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
			@RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sortType", defaultValue = "auto") String sortType,
					   Model model,
			ServletRequest request) {
		Map<String,Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
//		searchParams.put("EQ_deltag",EnumIsDelete.NOTDELETE.getCode());
//		searchParams.put("EQ_type", EnumMsgType.OTHER.getCode());
		Object gtdate = searchParams.get("GT_createDate");
		Object ltdate = searchParams.get("LTE_createDate");
		if(searchParams.get("GT_createDate") != null && StringUtils.isNotEmpty(searchParams.get("GT_createDate").toString()))
        {
            searchParams.put("GT_createDate", com.sdgakj.utils.DateUtil.formatStringToDate(searchParams.get("GT_createDate") + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
        }
        if(searchParams.get("LTE_createDate") != null && StringUtils.isNotEmpty(searchParams.get("LTE_createDate").toString()))
        {
            searchParams.put("LTE_createDate", com.sdgakj.utils.DateUtil.formatStringToDate(searchParams.get("LTE_createDate") + " 23:59:59", "yyyy-MM-dd HH:mm:ss"));
        }
        String value = "";

		Page<Message> msgs = messageService.getMessage(searchParams, pageNumber, pageSize, "createdate", sortType);
		model.addAttribute("msgs",msgs);
		model.addAttribute("sortType", sortType);
		searchParams.put("LIKE_opname",value);
		if(gtdate!=null){
			 searchParams.put("GT_createdate",gtdate);
		}
		if(ltdate!=null){
			 searchParams.put("LTE_createdate",ltdate);
		}
		model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
		return "msg/msgList";
	}
	
	/**
	 * 跳转添加页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value="create",method=RequestMethod.GET)
	public String  create(Model model){
		model.addAttribute("action", "create");
		return "msg/msgForm";
	}
	
	/**
	 * 跳转全体发布页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value="createall",method=RequestMethod.GET)
	public String createall(Model model){
		model.addAttribute("action","acreate");
		return "msg/msgAllForm";
	}
	
	/**
	 * 跳转修改页面
	 * @return
	 */
	@RequestMapping(value="update/{id}",method=RequestMethod.GET)
	public String update(@PathVariable("id") Long id, Model model){
		model.addAttribute("msg", messageService.getMessage(id));
		model.addAttribute("action", "update");
		return "msg/msgForm";
	}
	
	@RequestMapping(value="update",method=RequestMethod.POST)
	public String updateBrand(@Valid @ModelAttribute("msg")Message message, RedirectAttributes redirectAttributes){
		messageService.updateMessage(message);
		redirectAttributes.addFlashAttribute("message", "更新成功");
		return "redirect:/msg/list";
	}
	/**
	 * 发送消息
	 * @param type{create update}
	 */
	@RequestMapping(value="create",method=RequestMethod.POST)
	public String sendMsg(@RequestParam("type") String type, @RequestParam("mode") String mode,  @RequestParam("device") String device,@RequestParam("ddlIds") String[] ddlIds ,@RequestParam("msg") String msg ,@RequestParam("tag") String tag){
		//获取当前的发布人
	    ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		//Message message = messageService.productMessage(type, mode, device, ddlIds, msg, tag);
	    Message message = messageService.productMessage(type, mode, device, msg, tag,user.id);
		Long mid = message.getId();
		if(!EnumMsgType.OTHER.getCode().equals(type))
		{
			List<MessageUser> userList = new ArrayList<MessageUser>();
			if(ddlIds!=null && ddlIds.length>0){
				for(String uid:ddlIds){
					MessageUser msgUser = new MessageUser();
				    msgUser.setCreatedate(new Date());
				    msgUser.setDeltag(EnumIsDelete.NOTDELETE.getCode());
				    msgUser.setIsread("0");
				    msgUser.setUpdatedate(new Date());
				    msgUser.setMessage(new Message(Long.valueOf(mid)));
				    msgUser.setUserId(Long.valueOf(uid));
				    userList.add(msgUser);
				    if(EnumMsgType.ALIAS.getCode().equals(type)){
				    	JPushUtil.pushByAlias("000000"+uid, msg,device);
				    }else if(EnumMsgType.TAG.getCode().equals(type)){
				    	JPushUtil.pushByTag("000000"+uid, msg,device);
				    }
				}
			}
			if(userList!=null && userList.size()>0){
			    messageUserService.saveList(userList);
			}
		}else{
			JPushUtil.pushByAll(msg, type);
		}
		return "redirect:/msg/list";
	}
	
	/**
	 * 全部注册用户发布
	 * @param msg
	 * @return
	 */
	@RequestMapping(value="/acreate",method=RequestMethod.POST)
	public String sendMsg( @RequestParam("msg") String msg){

		JPushUtil.pushAllUser(msg);

		return "redirect:/msg/list";
	}
	
	/**
	 * 删除
	 * @param id
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value="/delete/{id}",method=RequestMethod.GET)
	public String delete(@PathVariable("id") Long id,RedirectAttributes redirectAttributes){
		Message message = messageService.getMessage(id);
		message.setDeltag(EnumIsDelete.DELETED.getCode()); //设置已经删除
		messageService.deleteMessage(id);
		this.messageUserService.deleteByMid(id);
		redirectAttributes.addFlashAttribute("message", "删除信息成功！");
		return "redirect:/msg/list";
	}

	/**
	 * 跳转添加页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value="toadd",method=RequestMethod.GET)
	public String  toadd(Model model){
		model.addAttribute("action", "sendtagmsg");
		Message msg = new Message();
		msg.setCreatedate(new Date());
		model.addAttribute("msg", msg);
		boolean serverFixFlag = false;
		List<Long> msgs = messageService.getMessageByType(3L, EnumIsDelete.NOTDELETE.getCode().toString(),"","");
		if(msgs != null && msgs.size() > 0) {
			serverFixFlag = true;
		}
		model.addAttribute("serverFixFlag", serverFixFlag);
		return "msg/toadd";
	}

	/**
	 * 发送消息
	 * @param type{create update}
	 */
	@RequestMapping(value="sendtagmsg",method=RequestMethod.POST)
	public String sendTagMsg(@RequestParam("type") String type, 
			@RequestParam("link") String link,
			@RequestParam("device") String device,
			@RequestParam("msg") String msg,
			@RequestParam("tag") String tag,
			@RequestParam("title") String title,
			@RequestParam("createdate") String createdate)
	{
	    ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
//	    final List<Object>  ddlIds = customorService.getAllCustomor();
		return "redirect:/msg/list";
	}
	
	@RequestMapping(value="/view/{id}",method=RequestMethod.GET)
	public String view(@PathVariable("id") Long id, Model model){
		model.addAttribute("msg", messageService.getMessage(id));
		return "msg/view";
	}
}
